#!/bin/bash
# 自行修改版本
TAG="v2.1.0"

# 定义JSON文件和输出文件的位置
json_file="update/latest.json"

TOKEN="${GITHUB_MAX_PAT}"
REPO="Gilinfen/Goyun"

# 如果找到资产URL，则下载文件
download_asset() {
  local FILE_NAME=$1
  local DEST_DIR=${2:-./}  # 如果未提供第二个参数，则默认为当前目录 "./"

  # 确保目录路径以 / 结尾
  [[ "$DEST_DIR" != */ ]] && DEST_DIR="$DEST_DIR/"
  # 如果目录不存在，则创建它
  mkdir -p "$DEST_DIR"

  # 查询发布信息以获取文件的下载 URL
  ASSET_URL=$(curl -H "Authorization: token $TOKEN" \
    "https://api.github.com/repos/$REPO/releases/tags/$TAG" | jq -r ".assets[] | select(.name == \"$FILE_NAME\") | .url")

  if [ -n "$ASSET_URL" ]; then
    # 根据提供的目录参数保存文件
    curl -H "Authorization: token $TOKEN" -H "Accept: application/octet-stream" -L -o "${DEST_DIR}${FILE_NAME}" "$ASSET_URL"
  else
    echo "File not found in release assets."
  fi
}

download_asset "latest.json"

new_json_file="./latest.json"

# 读取 darwin-x86_64 的值
darwin_x86_64_value=$(jq '.platforms["darwin-x86_64"]' $new_json_file)

# 添加 darwin-aarch64 字段并设置为 darwin-x86_64 的值
jq --argjson darwin_aarch64_value "$darwin_x86_64_value" '.platforms["darwin-aarch64"] = $darwin_aarch64_value' $new_json_file > temp.json && mv temp.json $json_file

# 先定义变量以便复用
old_url="https://github.com/Gilinfen/Goyun/releases/download"
new_url="https://gitee.com/gao-ling-feng/guyun_download/releases/download"

# 使用 sed 替换 latest.json 中的 URL
# sed -i "s|$old_url|$new_url|g" latest.json

# 如果你在 macOS 上运行这个脚本，sed 的 -i 选项需要一个空字符串参数如下：
sed -i '' "s|$old_url|$new_url|g" $json_file

rm -f $new_json_file

echo "Updated JSON file with darwin-aarch64 platform."

echo "下载：Guyun_2.1.0_x64.dmg"
download_asset "Guyun_x64.app.tar.gz" "./target"
echo "下载：Guyun_2.1.0_x64.dmg"
download_asset "Guyun_2.1.0_x64.dmg" "./target"
echo "下载：Guyun_2.1.0_x64_en-US.msi"
download_asset "Guyun_2.1.0_x64_en-US.msi" "./target"
echo "下载：Guyun_2.1.0_x64_en-US.msi.zip"
download_asset "Guyun_2.1.0_x64_en-US.msi.zip" "./target"
